/*
 * @Author: Siogo
 * @Date: 2025-10-21 16:30:00
 * @LastEditors: Siogo 你的邮箱
 * @LastEditTime: 2025-10-23 15:08:32
 * @FilePath: /frontend/src/api/tb/role.ts
 * @Description: 角色管理 API
 */
import { Page, BasicQuery } from '../model/baseModel';
import { defHttp } from '/@/utils/http/axios';

// 角色数据结构
export interface Role {
  id?: {
    id: string;
    entityType: string;
  };
  roleId?: {
    id: string;
    entityType: string;
  } | null;
  name: string;
  menus?: string[];
  createdTime?: number;
}

// 角色查询参数
export interface RoleQuery extends BasicQuery {
  textSearch?: string;
}

// 权限树节点
export interface MenuTreeNode {
  name: string;
  zhName: string;
  children?: MenuTreeNode[];
}

// Mock 数据（在后端接口未完成前使用）
const USE_MOCK = import.meta.env.VITE_USE_MOCK === 'true' || false;

const mockRoles: Role[] = [
  {
    id: { id: '1', entityType: 'ROLE' },
    name: '设备管理员',
    menus: ['device', 'device:read', 'device:write', 'device:delete'],
    createdTime: Date.now() - 86400000 * 5,
  },
  {
    id: { id: '2', entityType: 'ROLE' },
    name: '只读用户',
    menus: ['device:read', 'dashboard:read'],
    createdTime: Date.now() - 86400000 * 3,
  },
  {
    id: { id: '3', entityType: 'ROLE' },
    name: '规则链管理员',
    menus: ['rule-chain', 'rule-chain:read', 'rule-chain:write'],
    createdTime: Date.now() - 86400000 * 1,
  },
];

/**
 * 获取角色列表（分页）
 * GET /api/roles
 */
export function getRoleList(params: RoleQuery) {
  if (USE_MOCK) {
    // Mock 数据响应
    return Promise.resolve({
      data: mockRoles.filter((role) => (params.textSearch ? role.name.includes(params.textSearch) : true)),
      totalPages: '1',
      totalElements: mockRoles.length,
      hasNext: false,
    } as Page<Role>);
  }

  return defHttp.get<Page<Role>>({
    url: '/api/roles',
    params,
  });
}

/**
 * 根据ID获取角色详情
 * GET /api/role/{roleId}
 */
export function getRoleById(roleId: string) {
  if (USE_MOCK) {
    const role = mockRoles.find((r) => r.id?.id === roleId);
    return Promise.resolve(role);
  }

  return defHttp.get<Role>({
    url: `/api/role/${roleId}`,
  });
}

/**
 * 创建或更新角色
 * POST /api/role
 */
export function saveRole(data: Role) {
  if (USE_MOCK) {
    // Mock 创建/更新逻辑
    if (data.roleId && data.roleId.id) {
      // 更新
      const index = mockRoles.findIndex((r) => r.id?.id === data.roleId?.id);
      if (index !== -1) {
        mockRoles[index] = {
          ...data,
          id: { id: data.roleId.id, entityType: 'ROLE' },
        };
        return Promise.resolve(mockRoles[index]);
      }
    } else {
      // 创建（roleId 为 null）
      const newRole: Role = {
        ...data,
        id: { id: String(mockRoles.length + 1), entityType: 'ROLE' },
        createdTime: Date.now(),
      };
      mockRoles.push(newRole);
      return Promise.resolve(newRole);
    }
  }

  return defHttp.postJson<Role>({
    url: '/api/role',
    data,
  });
}

/**
 * 删除角色
 * DELETE /api/role/{roleId}
 */
export function deleteRole(roleId: string) {
  if (USE_MOCK) {
    const index = mockRoles.findIndex((r) => r.id?.id === roleId);
    if (index !== -1) {
      mockRoles.splice(index, 1);
    }
    return Promise.resolve();
  }

  return defHttp.delete<void>({
    url: `/api/role/${roleId}`,
  });
}

/**
 * 获取菜单权限树
 * GET /api/menu/tree
 */
export function getMenuTree() {
  if (USE_MOCK) {
    // Mock 权限树数据（使用 name/zhName 字段）
    const mockTree: MenuTreeNode[] = [
      {
        name: 'device',
        zhName: '设备管理',
        children: [
          { name: 'device:read', zhName: '查看设备' },
          { name: 'device:write', zhName: '编辑设备' },
          { name: 'device:delete', zhName: '删除设备' },
        ],
      },
      {
        name: 'rule-chain',
        zhName: '规则引擎',
        children: [
          { name: 'rule-chain:read', zhName: '查看规则链' },
          { name: 'rule-chain:write', zhName: '编辑规则链' },
        ],
      },
      {
        name: 'dashboard',
        zhName: '仪表板',
        children: [
          { name: 'dashboard:read', zhName: '查看仪表板' },
          { name: 'dashboard:write', zhName: '编辑仪表板' },
        ],
      },
    ];
    return Promise.resolve(mockTree);
  }

  return defHttp.get<MenuTreeNode[]>({
    url: '/api/menu/tree',
  });
}

/**
 * 获取当前用户可访问的菜单路由列表
 * GET /api/menu/current
 * @returns 返回路由名称数组
 */
export function getCurrentUserMenus() {
  if (USE_MOCK) {
    // Mock 数据：返回示例路由名称数组
    const mockMenus: string[] = [
      'DeviceList',
      'DeviceProfileList',
      'AssetList',
      'AssetProfileList',
      'DashboardList',
      'AlarmList',
      'RuleChainList',
      'CustomerUserList',
      'RoleList',
    ];
    return Promise.resolve(mockMenus);
  }

  return defHttp.get<string[]>({
    url: '/api/menu/current',
  });
}

/**
 * 获取角色关联的用户列表
 * GET /api/role/{roleId}/users
 */
export function getRoleUsers(roleId: string, params: BasicQuery) {
  return defHttp.get<Page<any>>({
    url: `/api/role/${roleId}/users`,
    params,
  });
}
